// ==UserScript==
// @name            Mushify It
// @namespace       http://code.google.com/p/mushify-it
// @description     Mushify It
// @match           http://mush.vg/
// @match           http://mush.vg/#
// @require         http://code.jquery.com/jquery.min.js
// @require         http://mushify-it.googlecode.com/svn/trunk/lib/markitup/jquery.markitup.js
// @resource        markitupCSS http://mushify-it.googlecode.com/svn/trunk/lib/markitup/skins/mush/style.css?nocache=201301251614
// @updateURL       http://mushify-it.googlecode.com/files/mushifyIt.user.js
// @version         0.2
// ==/UserScript==

// Nous sommes sur une page avec les onglets de chat
if ($('#chatBlock')) {

    var $$ = unsafeWindow.jQuery;

    // Constants

    var SETTING_COLORIZE_CHARACTERS = "mushifyIt.colorizeCharacters";
    var SETTING_MARKUP = "mushifyIt.markup";

    var CHARACTERS = {
        'JIN SU': {color: '#9c364b'},
        'FRIEDA': {color: '#477f39'},
        'KUAN TI': {color: '#bf6c20'},
        'JANICE': {color: '#d44758'},
        'ROLAND': {color: '#6f3951'},
        'HUA': {color: '#ae4319'},
        'PAOLA': {color: '#b03da4'},
        'CHAO': {color: '#33398a'},
        'FINOLA': {color: '#36759b'},
        'STEPHEN': {color: '#5d4833'},
        'IAN': {color: '#9c813e'},
        'CHUN': {color: '#446d5d'},
        'RALUCA': {color: '#5a5a53'},
        'GIOELE': {color: '#da6e2d'},
        'ELEESHA': {color: '#3a4318'},
        'TERRENCE': {color: '#822834'},
        'NERON': {color: '#d1003b'}
    };

    var MARKITUP_SETTINGS = {
        nameSpace: 'mush', // Useful to prevent multi-instances CSS conflict
        resizeHandle: false,
        markupSet: [
            {name:'Bold', className: "bold", key:'B', openWith:'[b]', closeWith:'[/b]'},
            {name:'Italic', className: "italic", key:'I', openWith:'[i]', closeWith:'[/i]'},
            {name:'Quotes', className: "quotes", openWith:'[cite]', closeWith:'[/cite]'},
            {separator:'---------------' },
            {name:'Gadgets RP', className: 'gadgets-rp', key:'g', dropMenu :[
                {name:'Carte', className: 'card', replaceWith:'{carte}'},
                {name:'Consonne', className: 'conson', replaceWith:'{consonne}'},
                {name:'Voyelle', className: 'vowel', replaceWith:'{voyelle}'},
                {name:'Dé 10', className: 'dice10', replaceWith:'{d10}'},
                {name:'Dé 100', className: 'dice100', replaceWith:'{d100}'},
                {name:'Dé 12', className: 'dice12', replaceWith:'{d12}'},
                {name:'Dé 20', className: 'dice20', replaceWith:'{d20}'},
                {name:'Dé 4', className: 'dice4', replaceWith:'{d4}'},
                {name:'Dé 6', className: 'dice6', replaceWith:'{d6}'},
                {name:'Dé 8', className: 'dice8', replaceWith:'{d8}'},
                {name:'Lettre', className: 'letter', replaceWith:'{lettre}'},
                {name:'Pile ou face', className: 'pf', replaceWith:'{pf}'},
                {name:'Pierre-Feuille-Ciseaux', className: 'rps', replaceWith:'{pfc}'}
            ]},
            {name:'Smileys', className: 'smileys', key:'s', dropMenu :[
                {name:'Commandant', className: 'commander', replaceWith:':commander:'},
                {name:'Responsable communication', className: 'resp_comm', replaceWith:':resp_comm:'},
                {name:'Admin Néron', className: 'admin_neron', replaceWith:':admin_neron:'},
                {name:'Alerte', className: 'alert', replaceWith:':alert:'},
                {name:'Asocial', className: 'asocial', replaceWith:':asocial:'},
                {name:'Affamé', className: 'hungry', replaceWith:':hungry:'},
                {name:'Poubelle', className: 'bin', replaceWith:':bin:'},
                {name:'Caliméro', className: 'calim', replaceWith:':calim:'},
                {name:'Communication', className: 'com', replaceWith:':com:'},
                {name:'Handicapé', className: 'disabled', replaceWith:':disabled:'},
                {name:'Porte', className: 'door', replaceWith:':door:'},
                {name:'Point de vie', className: 'pv', replaceWith:':pv:'},
                {name:'Point d\'action', className: 'pa', replaceWith:':pa:'},
                {name:'Point de mouvement', className: 'pm', replaceWith:':pm:'},
                {name:'Point de moral', className: 'pmo', replaceWith:':pmo:'},
                {name:'Moral faible', className: 'psy_disease', replaceWith:':psy_disease:'},
                {name:'Plante malade', className: 'plant_diseased', replaceWith:':plant_diseased:'},
                {name:'Plante asséchée', className: 'plant_dry', replaceWith:':plant_dry:'},
                {name:'Plante assoifée', className: 'plant_thirsty', replaceWith:':plant_thirsty:'},
                {name:'Jeune plante', className: 'plant_youngling', replaceWith:':plant_youngling:'},
                {name:'XP', className: 'xp', replaceWith:':xp:'},
                {name:'Triomphe', className: 'triumph', replaceWith:':triumph:'},
                {name:'Triomphe Vaisseau', className: 'ship_triumph', replaceWith:':ship_triumph:'},
                {name:'Chat', className: 'cat', replaceWith:':cat:'},
                {name:'Chut', className: 'chut', replaceWith:':chut:'},
                {name:'Mort', className: 'dead', replaceWith:':dead:'},
                {name:'Feu', className: 'fire', replaceWith:':fire:'},
                {name:'O2', className: 'o2', replaceWith:':o2:'},
                {name:'Fuel', className: 'fuel', replaceWith:':fuel:'},
                {name:'Hunter', className: 'hunter', replaceWith:':hunter:'},
                {name:'Lit', className: 'laid', replaceWith:':laid:'},
                {name:'Garde', className: 'mastered', replaceWith:':mastered:'},
                {name:'Mush', className: 'mush', replaceWith:':mush:'},
                {name:'PA Ordinateur', className: 'pa_comp', replaceWith:':pa_comp:'},
                {name:'PA Cuisine', className: 'pa_cook', replaceWith:':pa_cook:'},
                {name:'PA Néron', className: 'pa_core', replaceWith:':pa_core:'},
                {name:'PA Réparation', className: 'pa_eng', replaceWith:':pa_eng:'},
                {name:'PA Soin', className: 'pa_heal', replaceWith:':pa_heal:'},
                {name:'PA Pilgred', className: 'pa_pilgred', replaceWith:':pa_pilgred:'},
                {name:'PA Tir', className: 'pa_shoot', replaceWith:':pa_shoot:'},
                {name:'Médicament', className: 'pills', replaceWith:':pills:'},
                {name:'Puanteur', className: 'stink', replaceWith:':stink:'},
                {name:'Parler', className: 'talk', replaceWith:':talk:'},
                {name:'Talky', className: 'talky', replaceWith:':talky:'},
                {name:'Temps', className: 'time', replaceWith:':time:'},
                {name:'Aide', className: 'tip', replaceWith:':tip:'},
                {name:'Plus', className: 'more', replaceWith:':more:'},
                {name:'Moins', className: 'less', replaceWith:':less:'}
            ]},
            {separator:'---------------' },
            {name:'Clean', className:"clean", replaceWith:function(h) { return h.selection.replace(/\[(.*?)\]/g, "") } }
        ]
    };

    // Add css file

    var markitupCSS = GM_getResourceText("markitupCSS");
    GM_addStyle(markitupCSS);

    function addGlobalStyle(css) {
     		try {
     			var elmHead, elmStyle;
     			elmHead = document.getElementsByTagName('head')[0];
     			elmStyle = document.createElement('style');
     			elmStyle.type = 'text/css';
     			elmHead.appendChild(elmStyle);
     			elmStyle.innerHTML = css;
     		} catch (e) {
     			if (!document.styleSheets.length) {
     				document.createStyleSheet();
     			}
     			document.styleSheets[0].cssText += css;
     		}
     	}

    // Redéfinition de Main.resetJs
    // Appelé en callback après une actualisation du chat
    // Le chatForm n'est pas reseté
    var parentResetJs = unsafeWindow.Main.resetJs;
    unsafeWindow.Main.resetJs = function (doActions) {
        parentResetJs(doActions);
        onChatReload();
    }

    // Redéfinition de Main.loadMoreWall
    // Très moche, mais pas moyen de choper le callback autrement...
    unsafeWindow.Main.loadMoreWall = function (jq) {
    if (unsafeWindow.Main.lmwProcessing) return;
        unsafeWindow.Main.lmwProcessing = true;
        var w = $$(".cdLast");
        var wp = w.closest(".wall");
        if(w.length > 0) {
            unsafeWindow.JqEx.postLoading(wp);
            unsafeWindow.Tools.ping("/retrWallAfter/" + w.parent().data("k"),function(content) {
                var jq1 = $$(content);
                unsafeWindow.JqEx.remLoading(wp);
                w.removeClass("cdLast");

                var test = jq1.find(".wall");

                // Hook
                onChatReload(test);

                wp.append(test.html());
                unsafeWindow.Main.lmwProcessing = false;
            });
        }
    }

    var initFunctions = [];
    var reloadFunctions = [];

    // Init
    init();

    $$.each(initFunctions, function(index, value) {
        value();
    });

    mushifyChat();
    mushifyChatReply();

    // Fonctions à rappeler à chaque rechargement du wall
    // --------------------------------------------------------------------------

    function onChatReload() {

        $$.each(reloadFunctions, function(index, value) {
            value.fct.apply(null, value.args);
        });

        mushifyChatReply();
    }

    // Réglages
    // --------------------------------------------------------------------------

    function init() {

        // First launch

        if (localStorage[SETTING_MARKUP] == undefined) {
            localStorage[SETTING_MARKUP] = "true";
            localStorage[SETTING_COLORIZE_CHARACTERS] = "true";
        }

        $$('<a href="#" id="mushifyItSettingsButton" class="butmini">Réglages Mushify It</a>').appendTo('#chat_col');
        $$('<div id="mushifyItSettings" style="display: none"><table><tbody><tr><td><input type="checkbox" name="colorizeCharacters"> Colorier les personnages</td></tr><tr><td><input type="checkbox" name="markup"> Editeur de texte</td></tr></tbody></table></div>').appendTo('#chat_col');

        // colorizeCharacters
        $$('#mushifyItSettings input[name=colorizeCharacters]').click(function() {
            localStorage[SETTING_COLORIZE_CHARACTERS] = $$(this).is(':checked');
        });

        if (localStorage[SETTING_COLORIZE_CHARACTERS] == "true") {
            $$('#mushifyItSettings input[name=colorizeCharacters]').attr('checked', 'checked');

            initFunctions.push(colorizeCharacters);
            reloadFunctions.push({fct: colorizeCharacters, args: null});
        }

        // markup
        $$('#mushifyItSettings input[name=markup]').click(function() {
            localStorage[SETTING_MARKUP] = $$(this).is(':checked');
        });

        if (localStorage[SETTING_MARKUP] == "true") {
            $$('#mushifyItSettings input[name=markup]').attr('checked', 'checked');

            initFunctions.push(initMarkup);
            reloadFunctions.push({fct: reloadMarkup, args: null});
        }

        $$('#mushifyItSettingsButton').click(function() {
            $$('#mushifyItSettings').dialog({ position: { my: "left bottom", at: "left top", of: $$('#mushifyItSettingsButton') } });
            return false;
        });
    }

    // Amélioration du Chat
    // --------------------------------------------------------------------------

    function mushifyChat() {
        _resetTextarea();

        // Désactivation de la suppression automatique du message lors d'un focus
        unsafeWindow.Main.onChatFocus = function(){};
        unsafeWindow.Main.onWallFocus = function(){}

        // Désactivation de l'envoi d'un message vide
        $$('.chatForm > textarea.chatbox').removeAttr('onkeydown');
        $$('.chatForm > textarea.chatbox').bind('keydown', function(e) {
            if (e.which == 13 && !e.ctrlKey && $$(this).val().trim() == '') {
                e.preventDefault();
            } else {
                if (e.which == 13) {
                    if (!e.ctrlKey) $$(this).parent().submit(); else $$(this).val($$(this).val() + "\r\n");
                }
            }
        });

        $$('.chatForm > textarea.chatbox').bind('keyup', function(e) {
            if ($$(this).val().trim() == '') {
                $$('input.chatbutton').hide();
            } else {
                $$('input.chatbutton').show();
            }
        });
    }

    function mushifyChatReply() {
        _resetTextarea();

        // Désactivation de l'envoi d'une réponse vide
        $$('.reply > textarea.chatbox').removeAttr('onkeydown');

        $$('.reply > textarea.chatbox').bind('keydown', function(e) {
            if (e.which == 13 && !e.ctrlKey && $$(this).val().trim() == '') {
                e.preventDefault();
            } else {
                unsafeWindow.Main.onWallInput(e);
            }
        });
    }

    function _resetTextarea() {
        // Reset des textareas
        $$('textarea.chatbox').attr('placeholder', 'Mon message ici !');
        $$('textarea.chatbox').val('');
    }

    // Colorier les pseudos des joueurs sur le wall
    // --------------------------------------------------------------------------

    function colorizeCharacters() {
        $$('#chatBlock .what_happened strong, #chatBlock .private .what_happened strong').each(function() {
            var characterName = $$(this).text().toUpperCase();

            var character = CHARACTERS[characterName];
            if (character != null) $$(this).css({color: character.color});
        });

        $$('#chatBlock').find('.buddy').each(function() {
            var characterName = $$(this).text();
            characterName = characterName.substr(0, characterName.length - 1).toUpperCase().trim();

            var character = CHARACTERS[characterName];
            if (character != null) $$(this).css({color: character.color});
        });
    }

    // Ajout d'un éditeur de texte
    // --------------------------------------------------------------------------

    function initMarkup() {

        $$('<div id="markItUpEditorDialog" title="Editeur de texte"><textarea id="markItUpEditor" class="markItUpEditor"></textarea></div>').appendTo('body');
        _prepareEditorDialog();
        $('#markItUpEditor').markItUp(MARKITUP_SETTINGS);

        _addMarkupButtons($$('#cdMainChat'));
    }

    function reloadMarkup() {
        _prepareEditorDialog();
        _addMarkupButtons($$('#chatBlock'));
    }

    function _prepareEditorDialog() {
        $$('#markItUpEditorDialog').dialog({
            autoOpen: false,
            buttons: {
                'Valider': function() {
                    currentTextarea.val($$('#markItUpEditor').val()).trigger('keyup');
                    $$(this).dialog('close');
                }
            },
            close : function() {
                $$('.chatbox').attr('readonly', false);
                currentTextarea.focus();
            },
            minHeight: 410,
            minWidth: 510
        });
    }

    function _addMarkupButtons($parent) {

        $$('<a class="mushifyTextEditorButton butmini" href="#" style="float: left; margin-left: 8px;">Editeur</a>').insertAfter($parent.find('.chatbox'));

        $$('#cdMainChat .mushifyTextEditorButton').click(function() {
            if (!$$('#markItUpEditorDialog').dialog('isOpen')) {
                currentTextarea = $$(this).prev();
                $$('.chatbox').attr('readonly', true);
                $$('#markItUpEditor').val(currentTextarea.val());
                $$('#markItUpEditorDialog').dialog('open');
            }
            return false;
        });
    }

    // Déplacement du markasread
    // --------------------------------------------------------------------------

    $$('.readeverything').prependTo('.rightbg').css({'float': 'right', 'margin': '0 10px 5px 0'});

}